package com.ecjtu.stadiumre_servations.service.impl;

import com.ecjtu.stadiumre_servations.response.Result;
import com.ecjtu.stadiumre_servations.service.MinioService;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class MinioServiceImpl implements MinioService {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket}")
    private String bucketName;

    // 初始化存储桶
    @Override
    public Result<Void> initBucket() {
        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
            return Result.ok();
        } catch (Exception e) {
            return Result.fail(500, "Failed to initialize bucket: " + e.getMessage());
        }
    }

    // 上传文件
    @Override
    public Result<String> uploadFile(MultipartFile file) {
        try {
            String objectName = System.currentTimeMillis() + "_" + file.getOriginalFilename();

            // 统一图片尺寸为640x360
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            Thumbnails.of(file.getInputStream())
                    .size(640, 360)
                    .keepAspectRatio(false) // 强制裁剪为指定尺寸
                    .toOutputStream(outputStream);
            byte[] imageBytes = outputStream.toByteArray();
            ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);

            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .stream(inputStream, imageBytes.length, -1)
                    .contentType(file.getContentType())
                    .build());
            return Result.ok(objectName);
        } catch (Exception e) {
            return Result.fail(500, "Failed to upload file: " + e.getMessage());
        }
    }

    // 下载文件
    @Override
    public Result<InputStream> downloadFile(String objectName) {
        try {
            InputStream stream = minioClient.getObject(GetObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .build());
            return Result.ok(stream);
        } catch (Exception e) {
            return Result.fail(500, "Failed to download file: " + e.getMessage());
        }
    }

    // 删除文件
    @Override
    public Result<Void> deleteFile(String objectName) {
        try {
            minioClient.removeObject(RemoveObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .build());
            return Result.ok();
        } catch (Exception e) {
            return Result.fail(500, "Failed to delete file: " + e.getMessage());
        }
    }

    // 获取文件URL
    @Override
    public Result<String> getFileUrl(String objectName) {
        try {
            String url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                    .method(Method.GET)
                    .bucket(bucketName)
                    .object(objectName)
                    .expiry(60 * 60) // 1小时有效期
                    .build());
            return Result.ok(url);
        } catch (Exception e) {
            return Result.fail(500, "Failed to get file URL: " + e.getMessage());
        }
    }

    // 列出所有存储桶
    @Override
    public Result<List<Bucket>> listBuckets() {
        try {
            List<Bucket> buckets = minioClient.listBuckets();
            return Result.ok(buckets);
        } catch (Exception e) {
            return Result.fail(500, "Failed to list buckets: " + e.getMessage());
        }
    }
    @Override
    public Result<List<String>> listImages() {
        try {
            Iterable<io.minio.Result<Item>> results = minioClient.listObjects(
                    ListObjectsArgs.builder()
                            .bucket(bucketName)
                            .build()
            );
            List<String> imageUrls = new ArrayList<>();
            for (io.minio.Result<Item> result : results) {
                Item item = result.get();
                String objectName = item.objectName();
                String url = minioClient.getPresignedObjectUrl(
                        GetPresignedObjectUrlArgs.builder()
                                .method(Method.GET) // 必须加
                                .bucket(bucketName)
                                .object(objectName)
                                .build()
                );
                imageUrls.add(url);
            }
            return Result.ok(imageUrls);
        } catch (Exception e) {
            return Result.fail(500, "获取图片列表失败: " + e.getMessage());
        }
    }
    }